<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button type="warning" :loading="exportLoading" icon="el-icon-upload2" size="small" class="item-gap" @click="onExportExcel">导出</jk-button>
					<jk-button type="warning" :loading="exportLoading" icon="el-icon-upload2" size="small" class="item-gap" @click="onDerivedpart">导出2</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :clearable="false" :option-list="workshopList" placeholder="区域" class="search-bar-item-size2 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<jk-select v-model="searchParams.groupId" clearable :option-list="groupList" placeholder="班组" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.processCodeList" multiple :collapse-tags="true" value-key-name="code" clearable :option-list="processList" placeholder="工序" class="search-bar-item-size3 margin-5-0 item-gap"></jk-select>
					<div class="search-bar-item-size2 item-gap">
						<el-date-picker v-model="searchParams.yearMonth" :clearable="false" size="small" style="width: 100%;" type="month" value-format="yyyy-MM" placeholder="月" />
					</div>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="frontGroupSalaryMonthReportTable"
				show-footer
				:loading="tableLoading"
				:span-method="mergeColMethod"
				:footer-method="footerMethod"
				border
				:stripe="false"
				:data="tableData"
				:height="tableHeight + 30"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.value"
					:align="item.align"
					:field="item.key"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<!--表头-->
					<template v-if="!['empName', 'processName'].includes(item.key)" slot="header">
						<div class="flex-end-center">
							<div style="display: flex;flex-direction: column;justify-content: center;align-items: center;line-height: 13px;font-weight: 500;">
								<span>{{ item.value ? item.value.split(' ')[0] : '' }}</span>
								<span style="color: #808695;">{{ item.value ? item.value.split(' ')[1] : '' }}</span>
							</div>
						</div>
					</template>
					<template slot-scope="scope">
						<span v-if="item.key === 'code'">{{ scope.row.code }}</span>
						<span v-else>{{ scope.row[scope.column.property] }}</span>
					</template>
				</vxe-column>
			</jk-table>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatMonth, formatDate, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import XEUtils from 'xe-utils';
    import { personnelGroupPage } from '../../../api/personnel/group';
    import { productionGroupProductionSalarySalaryMonth } from '../../../api/production/reports';
    import { systemUserColumnConfigGet } from '@/api/system/column-config';
    // import field from './field.js';
    export default {
        name: 'MonthlyWages',
        components: {},
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': productionGroupProductionSalarySalaryMonth
                },
                totalData: {
                    totalOutputM: 0,
                    totalOutputKg: 0
                },
                groupList: [],
                processList: [],
                tableData: [],
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                count: 0,
                searchParams: {
                    yearMonth: '',
                    processCodeList: [],
                    workshopId: null
                }
            };
        },
        methods: {
            onWorkshopChange() {
                this.$set(this.searchParams, 'groupId', null);
                this.tableData = [];
                this.getGroupListRequest();
            },
            onExportExcel() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                if (params.yearMonth) {
                    params.year = new Date(params.yearMonth).getFullYear();
                    params.month = new Date(params.yearMonth).getMonth() + 1;
                }
                this.apiItem.page(params).then(res => {
                    if (res.data.status === 200) {
            import('@/vendor/Export2Excel').then(excel => {
              const titleList = this.tableColumnList.map(x => x.value);
              const keyList = this.tableColumnList.map(x => x.key);
              const dataList = res.data.res.tableData ? res.data.res.tableData : [];
              // 合计项
              const totalItem = {};
              keyList.forEach((x, idx) => {
                totalItem[x] = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0][idx];
              });
              dataList.push(totalItem);
              const data = dataList.map(v => keyList.map(j => v[j]));
              excel.export_json_to_excel({
                header: titleList,
                data,
                filename: `${this.$route.meta.title}(${formatDate(this.searchParams.yearMonth, '')})`,
                autoWidth: true,
                bookType: 'xlsx'
              });
            });
                    }
                    this.exportLoading = false;
                });
            },
            onDerivedpart() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                if (params.yearMonth) {
                    params.year = new Date(params.yearMonth).getFullYear();
                    params.month = new Date(params.yearMonth).getMonth() + 1;
                }
                this.apiItem.page(params).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        if (resData.tableHeader) {
                            const keys = [];
                            const forfilename = [];
                            // field.fieldNane.forEach((x) => {
                            //     forfilename.push(x.name);
                            // });
                            resData.tableHeader.filter(x => {
                                if (forfilename.includes(x.value)) {
                                    keys.push(x.key);
                                }
                                return forfilename.includes(x.value);
                            });
              import('@/vendor/Export2Excel').then(excel => {
                const dataList = res.data.res.tableData ? res.data.res.tableData : [];
                // 合计项
                const totalItem = {};
                const totalprocess = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0].slice(0, 2);
                const nightsubsidy = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0].slice(-9);
                const processoverall = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0].slice(-11).slice(0, 1);
                const Topeight = nightsubsidy.slice(0, 7);
                const nightdays = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0].slice(-1);
                const arr = [...totalprocess, ...processoverall, ...Topeight, ...nightdays];
                keys.forEach((x, idx, ary) => {
                  totalItem[x] = arr[idx];
                });
                dataList.push(totalItem);
                const data = dataList.map(v => keys.map(j => v[j]));
                excel.export_json_to_excel({
                  header: forfilename,
                  data,
                  filename: `${this.$route.meta.title}(${formatDate(this.searchParams.yearMonth, '')})`,
                  autoWidth: true,
                  bookType: 'xlsx'
                });
              });
                        }
                    }
                    this.exportLoading = false;
                });
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return `合计: `;
                        }
                        if (!['empName', 'processName'].includes(column.property)) {
                            return XEUtils.sum(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const prevRow = visibleData[_rowIndex - 1];
                let nextRow = visibleData[_rowIndex + 1];
                if (column.property === 'belongDate') {
                    if (prevRow && prevRow.belongDate === row.belongDate) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.belongDate === row.belongDate) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getGroupListRequest() {
                if (this.searchParams.workshopId) {
                    return personnelGroupPage({
                        workshopId: this.searchParams.workshopId,
                        auditState: 1
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.groupList = res.data.res;
                        }
                    });
                }
            },
            async getDependentData() {
                this.tableLoading = true;
                this.$set(this.searchParams, 'yearMonth', formatMonth(Date.now()));
                await this.getGroupListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                if (this.searchParams.workshopId && this.searchParams.yearMonth) {
                    this.tableLoading = true;
                    this.tableColumnList = [];
                    const params = { ...this.searchParams };
                    if (params.yearMonth) {
                        params.year = new Date(params.yearMonth).getFullYear();
                        params.month = new Date(params.yearMonth).getMonth() + 1;
                    }
                    return this.apiItem['page'](params).then(res => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            const resData = res.data.res || {};
                            this.count = res.data.count;
                            const arr = [];
                            if (resData.tableHeader) {
                                resData.tableHeader.forEach(x => {
                                    x.value = x.value + '';
                                    if (x.key && Array.isArray(x.key)) {
                                        x.key.forEach(k => {
                                            arr.push({
                                                value: `${x.value} ${k.value}`,
                                                key: k.key,
                                                width: 100,
                                                align: 'right'
                                            });
                                        });
                                    } else {
                                        arr.push({
                                            value: x.value,
                                            key: x.key,
                                            fixed: ['empName', 'processName'].includes(x.key) ? 'left' : '',
                                            width: ['empName', 'processName'].includes(x.key) ? 80 : 120,
                                            align: ['empName', 'processName'].includes(x.key) ? 'left' : 'right'
                                        });
                                    }
                                    return x;
                                });
                            }
                            this.tableColumnList = arr;
                            this.tableData = resData.tableData ? resData.tableData : [];
                            this.totalData = resData.total;
                            this.$nextTick(() => {
                                // 修复底部每月1号合计计算错误的问题
                                this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.updateData();
                                this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.refreshColumn(true);
                            });
                        }
                    });
                }
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                if (this.searchParams.workshopId && this.searchParams.yearMonth) {
                    this.getListRequest();
                } else {
                    tipsBar(this, 'custom', 'warning', '区域、年月不能为空!');
                }
            }
        },
        mounted() {
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.processList = this.$store.state.user.userProcess.processList;
            // 默认前纺区域(页面缓存时，没有值的情况下再赋值)
            if (!this.searchParams.workshopId) {
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            }
            this.getDependentData();
        }
    };
</script>
<style>
</style>
